<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YOLOX</title>
</head>
<body>
    <h1>YOLOX目标检测</h1>
    <h2>图片上传</h2>
    <input type="file" id="imageInput" accept="image/*">
    <button onclick="uploadImage()">上传</button>
    <button onclick="callPython()">调用程序</button>
    <div id="output"></div>
    
    <script>
        var imageName;

        function uploadImage() {
            var fileInput = document.getElementById('imageInput');
            var file = fileInput.files[0];
            imageName = file.name; // 将文件名赋值给 imageName 变量
            imageName = imageName.split('.').slice(0, -1).join('.'); // 去除文件扩展名
            console.log(imageName); // 检查文件名是否正确获取

            // 显示上传的图片
            var imghead = document.getElementById('imghead');
            imghead.src = URL.createObjectURL(file);
        }

        function callPython() {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "http://127.0.0.1:5000/hello", true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("output").innerHTML = xhr.responseText;
                    // 开始检查是否在outdir目录下出现与imghead同名的图片
                    checkImageExist();
                }
            };
            
            var data = imageName + ".jpg"; // 添加文件扩展名
            xhr.send(JSON.stringify(data)); // 发送包含图片文件名的 JSON 数据
        }

        function checkImageExist() {
            var imgName = imageName + ".jpg";
            var interval = setInterval(function() {
                var img = new Image();
                img.onload = function() {
                    clearInterval(interval);
                    document.getElementById('rightimg').src = img.src;
                };
                img.src = "outdir/" + imgName; // 检查是否存在与imghead同名的图片
            }, 1000); // 每秒检查一次
        }
    </script>
    <table>
        <tr>
            <td>
                <h2>
                    初始图片:
                </h2>
            </td>
            <td>
                <h2>
                    结果:
                </h2>
            </td>
        </tr>
        <tr>
            <td><img src="" width="800" border="0" id="imghead"></td>
            <td><img src="" width="800" border="0" id="rightimg"></td>
        </tr>
    </table>
</body>
</html>
